package com.bj58.data.emailreports.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import com.bj58.data.emailreports.model.DataInfo;
import com.bj58.data.emailreports.service.DataInfoService;
import com.bj58.data.emailreports.utils.DateUtil;
import com.bj58.data.emailreports.utils.MailUtil;
import com.bj58.data.emailreports.utils.ResourcesUtil;
import com.bj58.data.emailreports.utils.TemplateMethodFactory;
import com.bj58.data.emailreports.utils.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.PathUtil;
/**
 * 代理商帖子日报
 * @author zhaoxiang
 *
 */
public class DataInfoController {
	private static Set<String> citySet = new HashSet<String>();
	//城市： 类别列表，已按第一列排序
	private Map<String,List<DataInfo>> HYDataMap =new HashMap<String,List<DataInfo>>(); 
	private Map<String,List<DataInfo>> FCDataMap =new HashMap<String,List<DataInfo>>();
	private Map<String,List<DataInfo>> ZPDataMap =new HashMap<String,List<DataInfo>>();
	
	//城市_类别: VO , 无序
	private Map<String,DataInfo> HYCityCateMap =new HashMap<String,DataInfo>();
	private Map<String,DataInfo> FCCityCateMap =new HashMap<String,DataInfo>();
	private Map<String,DataInfo> ZPCityCateMap =new HashMap<String,DataInfo>();
	
	private  DataInfoService infoService = ServiceLocator.get(DataInfoService.class);
	private String cityCon="'阿坝','阿克苏','安康','巴彦淖尔','巴中','白城','本溪','滨州','博尔塔拉','长治','郴州','承德','达州','大同','丹东','鄂州','恩施','防城港','抚州','甘孜','菏泽','固原','广安','广元','桂林','贵港','哈密','汉中','河源','鹤岗','呼伦贝尔','葫芦岛','怀化','鸡西','济源','揭阳','晋城','晋中','晋中 ','喀什','莱芜','凉山','辽阳','辽源','临汾','娄底','吕梁','茂名','梅州','眉山','攀枝花','盘锦','萍乡','濮阳','七台河','潜江','黔东南','黔西南','钦州','清远','衢州','三门峡','商洛','韶关','邵阳','沭阳','双鸭山','朔州','四平','宿迁','绥化','遂宁','随州','天门','铁岭','通化','通辽','铜川','乌海','乌兰察布','梧州','锡林郭勒','仙桃','咸宁','湘西','孝感','忻州','兴安盟','雅安','延安','阳江','阳泉','宜宾','益阳','永州','云浮','运城','枣庄','张家界','张家口','朝阳','周口','驻马店','资阳','白银','酒泉','陇南','平凉','庆阳','武威','张掖'";
	static{
		String[] citys={"阿坝","阿克苏","安康","巴彦淖尔","巴中","白城","本溪","滨州","博尔塔拉","长治","郴州","承德","达州","大同","丹东","鄂州","恩施","防城港","抚州","甘孜","菏泽","固原","广安","广元","桂林","贵港","哈密","汉中","河源","鹤岗","呼伦贝尔","葫芦岛","怀化","鸡西","济源","揭阳","晋城","晋中","晋中 ","喀什","莱芜","凉山","辽阳","辽源","临汾","娄底","吕梁","茂名","梅州","眉山","攀枝花","盘锦","萍乡","濮阳","七台河","潜江","黔东南","黔西南","钦州","清远","衢州","三门峡","商洛","韶关","邵阳","沭阳","双鸭山","朔州","四平","宿迁","绥化","遂宁","随州","天门","铁岭","通化","通辽","铜川","乌海","乌兰察布","梧州","锡林郭勒","仙桃","咸宁","湘西","孝感","忻州","兴安盟","雅安","延安","阳江","阳泉","宜宾","益阳","永州","云浮","运城","枣庄","张家界","张家口","朝阳","周口","驻马店","资阳","白银","酒泉","陇南","平凉","庆阳","武威","张掖"};
		Collections.addAll(citySet, citys);
	}

	public void initialData(String searchDate)throws Exception{
		String hasData = infoService.checkDataSource(searchDate);
		if(!"true".equals(hasData))
			throw new NullPointerException(hasData);
		setDataInfo(searchDate);
		setLastData(searchDate);
		
	}
	
	public void checkDataSource(String tableName,String condition)throws Exception{


	}
	
	/**中小城市帖子日报
	 * 
	 */
	public void setDataInfo(String searchDate)throws Exception{
//			String cityCon = "'大同','忻州','晋中','晋中','晋城','阳泉','临汾','运城','吕梁','朔州','长治','铜仁','黔东南','张家口','张家口','四平','黔西南','安顺'";
		//先查今日的数据，放入Map中，然后查昨日上周的数据，从Map中取出今日的数据set进同一个Vo;
		//黄页
		List<DataInfo>  HYDataList = infoService.getHYDataInfo(searchDate,  cityCon);
		if(HYDataList == null || HYDataList.isEmpty())
			throw new NullPointerException("黄页数据为空");
		for(DataInfo vo:HYDataList){
			String cityname=vo.getCity();
			String key=cityname;
			List<DataInfo> cityCateList = new ArrayList<DataInfo>();
			if(HYDataMap.containsKey(key))
				cityCateList = HYDataMap.get(key);
			cityCateList.add(vo);
			HYDataMap.put(key, cityCateList);
			HYCityCateMap.put(vo.getCity()+"_"+vo.getCate(), vo);
		}
		//房产
		List<DataInfo>  FCDataList = infoService.getFCDataInfo(searchDate, cityCon);
		if(FCDataList == null || FCDataList.isEmpty())
			throw new NullPointerException("房产数据为空");
		for(DataInfo vo:FCDataList){
			String cityname=vo.getCity();
			String key=cityname;
			List<DataInfo> cityCateList = new ArrayList<DataInfo>();
			if(FCDataMap.containsKey(key))
				cityCateList = FCDataMap.get(key);
			cityCateList.add(vo);
			FCDataMap.put(key, cityCateList);
			FCCityCateMap.put(vo.getCity()+"_"+vo.getCate(), vo);
		}
			
			//招聘
			List<DataInfo> ZPDataList = infoService.getZhaopinDataInfo(searchDate, cityCon); 
			List<DataInfo> JLDataList = infoService.getJianLiDataInfo(searchDate, cityCon); //简历数据
			if(ZPDataList == null || ZPDataList.isEmpty())
				throw new NullPointerException("招聘数据为空");
			if(JLDataList == null || JLDataList.isEmpty())
				throw new NullPointerException("简历数据为空");
			Map<String,DataInfo> JLDataMap =new HashMap<String,DataInfo>();
			for(DataInfo vo:JLDataList){
				String key = vo.getCity()+"_"+vo.getCate();
				JLDataMap.put(key, vo);
			}
			for (DataInfo vo : ZPDataList) {
				String key = vo.getCity();
				List<DataInfo> cityCateList = new ArrayList<DataInfo>();
				if (ZPDataMap.containsKey(key)){
					cityCateList = ZPDataMap.get(key);
					if(cityCateList.size()>31)
						continue;
				}
				DataInfo jianliInfo=JLDataMap.get(vo.getCity()+"_"+vo.getCate());
				if(jianliInfo != null){
					vo.setPCJianLiAdd(jianliInfo.getPCJianLiAdd());
					vo.setMJianLiAdd(jianliInfo.getMJianLiAdd());
					vo.setAPPJianLiAdd(jianliInfo.getAPPJianLiAdd());
					vo.setTotalJianLiAdd(jianliInfo.getTotalJianLiAdd());
					vo.setAddJianLiUser(jianliInfo.getAddJianLiUser());
				}
				cityCateList.add(vo);
				ZPDataMap.put(key, cityCateList);
				ZPCityCateMap.put(vo.getCity()+"_"+vo.getCate(), vo);
			}
	}
	
	private void setLastData(String searchDate) throws Exception{
		Date  sDate = DateUtil.strToDate(searchDate, "yyyy-MM-dd");
		String lastDate = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 1),"yyyy-MM-dd");
		String lastWeek = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 7),"yyyy-MM-dd");	
		List<String> dateList = new ArrayList<String>();
		dateList.add(lastDate);dateList.add(lastWeek);
		//昨日，上周
		for(String date: dateList){
			//黄页
			List<DataInfo>  HYDataList = infoService.getOneHYDataInfo(date,  cityCon);
			for(DataInfo vo:HYDataList){
				String key=vo.getCity()+"_"+vo.getCate();
				if(HYCityCateMap.containsKey(key)){
					DataInfo tmpVo=HYCityCateMap.get(key);
					if(date.equals(lastDate)){	//昨日
						tmpVo.setInfoAddLastDay(vo.getInfoAdd());
						tmpVo.setUserAddLastDay(vo.getUserAdd());
					}else{	//上周
						tmpVo.setInfoAddLastWeek(vo.getInfoAdd());
						tmpVo.setUserAddLastWeek(vo.getUserAdd());
					}
				}
			}
			//房产
			List<DataInfo>  FCDataList = infoService.getOneFCDataInfo(date, cityCon);
			for(DataInfo vo:FCDataList){
				String key=vo.getCity()+"_"+vo.getCate();
				if(FCCityCateMap.containsKey(key)){
					DataInfo tmpVo=FCCityCateMap.get(key);
					if(date.equals(lastDate)){	//昨日
						tmpVo.setInfoAddLastDay(vo.getInfoAdd());
						tmpVo.setUserAddLastDay(vo.getUserAdd());
					}else{	//上周
						tmpVo.setInfoAddLastWeek(vo.getInfoAdd());
						tmpVo.setUserAddLastWeek(vo.getUserAdd());
					}
				}
			}	
			//招聘
			List<DataInfo> ZPDataList = infoService.getOneZhaopinDataInfo(date, cityCon); 
			List<DataInfo> JLDataList = infoService.getJianLiDataInfo(date, cityCon); //简历数据
			for(DataInfo vo:ZPDataList){
				String key=vo.getCity()+"_"+vo.getCate();
				if(ZPCityCateMap.containsKey(key)){
					DataInfo tmpVo=ZPCityCateMap.get(key);
					if(date.equals(lastDate)){	//昨日
						tmpVo.setInfoAddLastDay(vo.getInfoAdd());
						tmpVo.setUserAddLastDay(vo.getUserAdd());
					}else{	//上周
						tmpVo.setInfoAddLastWeek(vo.getInfoAdd());
						tmpVo.setUserAddLastWeek(vo.getUserAdd());
					}
				}
			}	
			//简历
			for(DataInfo jianliInfo:JLDataList){
				String key=jianliInfo.getCity()+"_"+jianliInfo.getCate();
				if(ZPCityCateMap.containsKey(key)){
					DataInfo tmpVo=ZPCityCateMap.get(key);
					if(date.equals(lastDate)){	//昨日
						tmpVo.setPCJianLiAddLastDay(jianliInfo.getPCJianLiAdd());
						tmpVo.setMJianLiAddLastDay(jianliInfo.getMJianLiAdd());
						tmpVo.setAPPJianLiAddLastDay(jianliInfo.getAPPJianLiAdd());
						tmpVo.setTotalJianLiAddLastDay(jianliInfo.getTotalJianLiAdd());
						tmpVo.setAddJianLiUserLastDay(jianliInfo.getAddJianLiUser());
					}else{	//上周
						tmpVo.setPCJianLiAddLastWeek(jianliInfo.getPCJianLiAdd());
						tmpVo.setMJianLiAddLastWeek(jianliInfo.getMJianLiAdd());
						tmpVo.setAPPJianLiAddLastWeek(jianliInfo.getAPPJianLiAdd());
						tmpVo.setTotalJianLiAddLastWeek(jianliInfo.getTotalJianLiAdd());
						tmpVo.setAddJianLiUserLastWeek(jianliInfo.getAddJianLiUser());
					}
				}
			}	
		}
	}
	
	public void dataInfoReport(String tempContent,String emailAddress,String city,String cates,String searchDate) throws Exception{
			//velocity对象
			VelocityContext context = new VelocityContext();
			Object tools = TemplateMethodFactory.getInstance(VelocityTools.class);
			context.put("tools",tools);
			
			Date  sDate = DateUtil.strToDate(searchDate, "yyyy-MM-dd");
			String nowDate = DateUtil.getStringDate(sDate,"yyyy-MM-dd");
			String lastDate = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 1),"yyyy-MM-dd");
			String lastWeek = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 7),"yyyy-MM-dd");
			context.put("nowDate",nowDate.replace("-", "."));
			context.put("lastDate",lastDate.replace("-", "."));
			context.put("lastWeek",lastWeek.replace("-", "."));
			
			//黄页
			if(cates.contains("黄页")){
				List<DataInfo>  HYDataList = HYDataMap.get(city);
				context.put("HYDataList",HYDataList);
			}
			
			//房产
			if(cates.contains("房产")){
				List<DataInfo>  FCDataList = FCDataMap.get(city);
				context.put("FCDataList",FCDataList);
			}
			//招聘
			if(cates.contains("招聘")){
				List<DataInfo>  ZPDataList = ZPDataMap.get(city);
				context.put("ZPDataList",ZPDataList);
			}
			context.put("city",city);
			VelocityEngine velocity  = new VelocityEngine();
			Velocity.setProperty("input.encoding", "utf-8");
			Velocity.setProperty("output.encoding", "utf-8");
			StringWriter out = new StringWriter();
			try {
					velocity.evaluate(context, out, "", tempContent);
			} catch (Exception e) {            
				e.printStackTrace();
				throw e;
			}
			String content = out.toString();
			out.close();
			int result = MailUtil.javaMailSend("帖子数据日报-" + searchDate, content, emailAddress,null);
			if(result !=1 ){
				throw new Exception(city+"--"+emailAddress+" 发送失败!请检查邮箱是否正确!");
			}
	}
	
	
	public String getTempContent() throws Exception{
		//读取模板内容
		String filepath =PathUtil.getWFNamespaceFolder()+"/emailtemp/dataInfoReport.html";
		ResourcesUtil.setCharset(Charset.forName("utf-8"));
		FileInputStream inputStream = new FileInputStream(new File(filepath));
		String templateContext = ResourcesUtil.readString2(inputStream);
		inputStream.close();
		return templateContext;
	}
	
	
	public static void main(String[] args) {
		DataInfoController  controller = new DataInfoController();
		String searchDate = "";
		searchDate = DateUtil.getStringDate(DateUtil.getDateBefore(new Date(), 1),"yyyy-MM-dd");
		if(null != args && args.length > 0){
				if(args.length > 1 || !args[0].contains("-")){
					System.out.println("par error");
					System.exit(0);
				}
				searchDate =args[0].trim();
		}
		System.out.println(searchDate);
		try {
			controller.initialData(searchDate);	 //查数据
			String tempContent = controller.getTempContent(); //读模板
				
			String city="宜宾";
			String cates="黄页,招聘,房产";
			String emailAddr="guoxue@58.com";
			controller.dataInfoReport(tempContent,emailAddr,city,cates,searchDate);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
